//
//  PaintingDetailsViewController.swift
//  NDAi
//
//  Created by 丸子 on 2024/6/20.
//

import UIKit
import Photos

class PaintingDetailsViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {
    var model:PaintImageDataModel?
    var homeModel:CommunityModel?
    let viewModel = CommunityViewModel()
    let disposeBag = DisposeBag()
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 88
        tableView.register(cellWithClass: PaintingImageTableViewCell.self)
        tableView.register(cellWithClass: PaintingDescTableViewCell.self)
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: (kSafeHeight + 74), right: 0)
//        tableView.bounces = false
//        tableView.alwaysBounceVertical = false //此外，如果您想确保即使数据少于一屏时 UITableView 也不会弹性拉伸，可以将 alwaysBounceVertical 属性也设置为 false：
        return tableView
    }()
    
    private lazy var resetBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.normalBackgroundImage = UIImage(named: "icon_paninting_reset")
        return button
    }()
    
    private lazy var saveBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleForNormal = "下载/保存"
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
        button.backgroundColor = UIColor(hexString: "#25262B")
        button.allRound(24)
        return button
    }()
    
    private lazy var likeBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleColorForNormal = Theme.color.text_d1
        button.normalImage = UIImage(named: "icon_com_likeNor")
        button.selectedImage = UIImage(named: "icon_com_likeSel")
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
        button.backgroundColor = UIColor(hexString: "#DFE1E8")
        button.allRound(24)
//        button.contentEdgeInsets = UIEdgeInsets(top: 0, left: <#T##CGFloat#>, bottom: <#T##CGFloat#>, right: <#T##CGFloat#>)
        button.layoutButtonWithEdgeInsetsStyle(.Left, space: 8)
        return button
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.editNav(isCurrent: true)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.editNav(isCurrent: false)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.removeSubViewController_k(vcName: "PaintingGenerateViewController")
        initNav()
        self.view.addSubview(tableView)
        self.view.addSubview(saveBtn)
        self.tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
         
        if self.homeModel != nil {
            self.view.addSubview(likeBtn)
            likeBtn.snp.makeConstraints { make in
                make.bottom.equalTo(self.safeBottom).offset(-10)
                  make.leading.equalTo(saveBtn.snp.trailing).offset(10)
                  make.trailing.equalToSuperview().offset(-15)
                  make.height.equalTo(48)
            }

            saveBtn.snp.makeConstraints { make in
                make.bottom.equalTo(self.safeBottom).offset(-10)
                make.leading.equalToSuperview().offset(15)
                make.height.equalTo(48)
                make.width.equalTo(likeBtn.snp.width)
                 
            }
            
            likeBtn.titleForNormal = self.homeModel?.like_count?.formatted
            likeBtn.isSelected = self.homeModel?.is_like == 1 ? true : false
            
            likeBtn.setClosureTouchUpInside_k { [weak self] in
                if let model = self?.homeModel {
                    self?.viewModel.clickLike(model: model)
                }
            }
            self.viewModel.likeSubject.subscribe(onNext: { [weak self] type in
                if type == 0 {
                    self?.homeModel?.like_count! -= 1
                }else {
                    self?.homeModel?.like_count! += 1
                }
                self?.likeBtn.isSelected = type == 1 ? true : false
                self?.homeModel?.is_like = type
                self?.likeBtn.titleForNormal = self?.homeModel?.like_count?.formatted
            }).disposed(by: disposeBag)
        }else {
            self.view.addSubview(resetBtn)

            resetBtn.setClosureTouchUpInside_k { [weak self] in
                Appearance.shared.recordStyle = self?.model
                GlobalRx.jumpDrawSubject.onNext(())
                
                if self?.navigationController?.haveChildViewController_k(vcName: "PaintingPageViewController") == true { 
                    self?.navigationController?.popViewController(animated: true)
                }else {
                    let vc = PaintingPageViewController()
                    self?.navigationController?.pushViewController(vc)
                }
                
                
            }
            
            resetBtn.snp.makeConstraints { make in
                make.bottom.equalTo(self.safeBottom).offset(-10)
                make.leading.equalToSuperview().offset(15)
                make.height.equalTo(48)
                make.width.equalTo(110)
            }
            
            saveBtn.snp.makeConstraints { make in
                make.bottom.equalTo(self.safeBottom).offset(-10)
                make.leading.equalTo(resetBtn.snp.trailing).offset(10)
                make.trailing.equalToSuperview().offset(-15)
                make.height.equalTo(48)
            }
        }
        saveBtn.setClosureTouchUpInside_k { [weak self] in
            self?.saveImage()
        } 
        self.tableView.reloadData()
    }
     
    func shareResult() {
        var imageUrl = ""
        if self.model?.img_url != nil{
            imageUrl = self.model?.img_url ?? ""
        }else if self.homeModel?.img_url != nil {
            imageUrl = self.homeModel?.img_url ?? ""
        }
        // 假设 imageView 是你用 SDWebImage 加载图片的 UIImageView 实例
        let imageView = UIImageView()
        // 使用 SDWebImage 提供的方法来加载图片
        imageView.sd_imageIndicator = SDWebImageActivityIndicator.gray
        imageView.sd_setImage(with: URL(string: imageUrl), placeholderImage: nil, options: [], completed: { (image, error, cacheType, imageURL) in
            if let image = image {
                let items: [Any] = [image]
                let activityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil)
                // 如果是 iPad，设置 popoverPresentationController 的源视图
                if UIDevice.current.userInterfaceIdiom == .pad {
                    activityViewController.popoverPresentationController?.sourceView = self.view
                    // 这里可以设置弹出位置
                    activityViewController.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
                }
                self.present(activityViewController, animated: true, completion: nil)
            } else {
                NDProgressHUD.showError(title: "", subtitle: "图片加载失败，请稍后再试")
            }
        })
    }
    
    func saveImage(){
//        guard let imageUrl = self.model?.img_url else { return }
        var imageUrl = ""
        if self.model?.img_url != nil{
            imageUrl = self.model?.img_url ?? ""
        }else if self.homeModel?.img_url != nil {
            imageUrl = self.homeModel?.img_url ?? ""
        }
        let imageView = UIImageView()
        // 使用 SDWebImage 提供的方法来加载图片
        imageView.sd_imageIndicator = SDWebImageActivityIndicator.gray
        imageView.sd_setImage(with: URL(string: imageUrl), placeholderImage: nil, options: [], completed: { (image, error, cacheType, imageURL) in
            if let image = image {
                PHPhotoLibrary.requestAuthorization { status in
                    if status == .authorized {
                        // 保存图片到相册
                        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
                        print("图片已保存到相册")
                        NDProgressHUD.showSuccess(title: "", subtitle: "保存成功")
                    } else {
                        NDProgressHUD.showError(title: "", subtitle: "没有相册访问权限")
                    }
                }
            } else {
                NDProgressHUD.showError(title: "", subtitle: "图片加载失败，请稍后再试")
            }
        })
        
//        URLSession.shared.dataTask(with: URL(string: imageUrl)!) { data, response, error in
//               guard let data = data, error == nil else {
//                   NDProgressHUD.showError(title: "", subtitle: "下载图片失败:\(error?.localizedDescription)")
//                   return
//               }
//               // 创建 UIImage
//               if let image = UIImage(data: data) {
//                   // 请求相册权限
//                   PHPhotoLibrary.requestAuthorization { status in
//                       if status == .authorized {
//                           // 保存图片到相册
//                           UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
//                           print("图片已保存到相册")
//                           NDProgressHUD.showSuccess(title: "", subtitle: "保存成功")
//                       } else {
//                           NDProgressHUD.showError(title: "", subtitle: "没有相册访问权限")
//                       }
//                   }
//               } else {
//                   NDProgressHUD.showError(title: "", subtitle: "图片数据无效")
//               }
//           }.resume()
    }
    
    func initNav(){
        self.navigationItem.title = "绘画详情"
        self.view.backgroundColor = UIColor(hexString: "#F3F2F7")
        let rightBtn = UIButton(type: .custom)
        rightBtn.setImage(UIImage(named: "icon_painting_share"), for: .normal)
        let rightItem = UIBarButtonItem(customView: rightBtn)
        self.navigationItem.rightBarButtonItem = rightItem
        
        rightBtn.setClosureTouchUpInside_k { [weak self] in
            self?.shareResult()
        }
    }
   
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.item == 0 {
            let cell = tableView.dequeueReusableCell(withClass: PaintingImageTableViewCell.self, for: indexPath)
            if let model = self.model {
                cell.imageIV.sd_setImage(with: URL(string: model.img_url ?? ""), placeholderImage: UIImage(named: "ai_launch_logo"))
            }
            if let model = self.homeModel {
                cell.imageIV.sd_setImage(with: URL(string: model.img_url ?? ""), placeholderImage: UIImage(named: "ai_launch_logo"))
            }
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withClass: PaintingDescTableViewCell.self, for: indexPath)
            if let model = self.model {
                cell.contentLb.text = model.message ?? ""
                cell.styleLb.text = "图片风格: \((model.style_text ?? "").replacingOccurrences(of: "\n", with: ""))"
                cell.sizeLb.text = "图片尺寸: \(model.proportion_value ?? "")"
            }
            if let model = self.homeModel {
                cell.contentLb.text = model.data_desc ?? ""
                cell.styleLb.text = "图片风格: \((model.style_text ?? "").replacingOccurrences(of: "\n", with: ""))"
                cell.sizeLb.text = "图片尺寸: \(model.proportion_value ?? "")"
            }
            return cell
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.item == 0 {
            let screenWidth: CGFloat = UIScreen.main.bounds.width - 0
            let horizontalPadding: CGFloat = 0
            if let proportionValue = self.model?.proportion_value {
                if let height = calculateHeight(for: proportionValue, screenWidth: screenWidth, horizontalPadding: horizontalPadding) {
                    return height
                }
            }else if let proportionValue = self.homeModel?.proportion_value {
                if let height = calculateHeight(for: proportionValue, screenWidth: screenWidth, horizontalPadding: horizontalPadding) {
                    return height
                }
            }
            return UITableView.automaticDimension
        }else {
            return UITableView.automaticDimension
        }
    }
    
    
    
    func calculateHeight(for proportion: String, screenWidth: CGFloat, horizontalPadding: CGFloat) -> CGFloat? {
        // 解析比例字符串
        let components = proportion.split(separator: ":")
        guard components.count == 2,
              let widthRatio = Double(components[0]),
              let heightRatio = Double(components[1]) else {
            return nil
        }
        
        // 计算实际宽度
        let actualWidth = screenWidth - (2 * horizontalPadding)
        
        // 计算高度
        let height = actualWidth * CGFloat(heightRatio) / CGFloat(widthRatio)
        
        return height
    }

}
